package at.fhj.itm11.forum.service.impl;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;

import at.fhj.itm11.forum.data.RatingDAO;
import at.fhj.itm11.forum.model.Rating;
import at.fhj.itm11.forum.service.RatingService;
import at.fhj.itm11.forum.service.converter.DTOConverter;
import at.fhj.itm11.forum.service.converter.RatingDTOConverter;
import at.fhj.itm11.forum.service.dtos.RatingDTO;

@Stateless
@Named
public class RatingServiceImpl implements RatingService {
    
    @Inject
    @Named("ratingDAOImpl")
    private RatingDAO ratingDAO;
    
    public void rate(RatingDTO rDto) {
    	//convert back to entity (-> extend converter wit
    	RatingDTOConverter rConv = new RatingDTOConverter();
    	
    	ratingDAO.rate(rConv.convertToEntity(rDto));
    }
    
    public int[] getRatingStatistics(Long postId) {

		long positiveRatingCount = ratingDAO.findPositiveRatingCountForPost(postId);
		long negativeRatingCount = ratingDAO.findNegativeRatingCountForPost(postId);
		
		int[] result = new int[2];
		long totalRatings;
		if((totalRatings = positiveRatingCount + negativeRatingCount) == 0) {
			result[0] = 0;
			result[1] = 0;
		}
		else {
			result[0] = (int)((positiveRatingCount * 100f) / totalRatings);
			result[1] = (int)((negativeRatingCount * 100f) / totalRatings);
		}
		
		return result;
    }

	@Override
	public RatingDTO findRatingByRaterAndPost(Long userId, Long postId) {
		DTOConverter<RatingDTO, Rating> ratingConverter = new RatingDTOConverter();
		return ratingConverter.convertToDto(ratingDAO.findRatingByRaterAndPost(userId, postId));
	}
}
